package org.aeon.dao

import org.aeon.entity.Book

/**
 * @author:     MissingAeon
 * @date:       2024/1/18 17:00
 * @description: Book持久化类
 */
class BookDao : BasicDao<String, Book> {
    private companion object {
        val books = mutableMapOf<String, Book>()

        init {
            // 这里可以对数据初始化
            books += "10001" to Book("10001", "测试数据1", "测试人员", 60.5f)
            books += "10002" to Book("10002", "测试数据2", "测试人员", 60.5f)
            books += "10003" to Book("10003", "测试数据3", "测试人员", 60.5f)
            books += "10004" to Book("10004", "测试数据4", "测试人员", 60.5f)
            books += "10005" to Book("10005", "测试数据5", "测试人员", 60.5f)
            books += "10006" to Book("10006", "测试数据6", "测试人员", 60.5f)
        }
    }

    override fun insert(t: Book): Boolean {
        if (!books.containsKey(t.id)) {
            // 存入的数据不可以被修改，所以只会存入拷贝
            books += t.id to t.copy()
            return true
        }
        return false
    }

    override fun modify(t: Book): Boolean {
        if (books.containsKey(t.id)) {
            // 存入的数据不可以被修改，所以只会存入拷贝
            books += t.id to t.copy()
            return true
        }
        return false
    }

    override fun remove(t: Book): Boolean {
        if (books.containsKey(t.id)) {
            books.remove(t.id)
            return true
        }
        return false
    }

    override fun query(func: (Book) -> Boolean): List<Book> {
        return books.asSequence()
            .filter { func(it.value) }
            // 存入的数据不可被修改，这里只返回拷贝
            .map { it.value.copy() }
            .toList()
    }

    override fun queryById(k: String): Book? = books[k]

    override fun exist(k: String): Boolean = books.containsKey(k)

    override fun count(): Int = books.size
}
